#coding=utf-8
#@Time:2019\11\14 0014 17:40
#@Author:希哥
#@File:id_card.py
import sys
import mysql.connector
from datetime import date
from datetime import timedelta
import random, os
import requests
import re
from bs4 import BeautifulSoup
import sql

# MySQL相关设置
mysql_host = 'localhost'
mysql_user = 'root'
mysql_passwd = 'root'
mysql_port = '3306'
mysql_database = 'hupo'

#连接数据库
try:
    connect = mysql.connector.connect(host=mysql_host,user=mysql_user,password=mysql_passwd,db=mysql_database,port=mysql_port,charset="utf8")
    cursor = connect.cursor(buffered=True)
    print u"Message:连接数据库成功"
except:
    print u"Message:连接数据库失败"

#全局设置为UTF-8
reload(sys)
sys.setdefaultencoding('utf-8')



def idcard_generator(operator):
    try:
        import time
        now = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(time.time()))  # 数据产生日期
        # 爬虫获取随机身份证号码
        s = requests.session()
        index = s.get('https://www.tiebazhushou.com/')
        index_soup = BeautifulSoup(index.text, 'html.parser')
        # 通过正则取出身份证号码
        id_all = index_soup.find_all('table', class_='table table-hover table-bordered')
        idcard_all = str(id_all[0])
        id = re.findall(r'<td>(.+)</td>', idcard_all)
        name = str(id[0])
        idcard = id[1]
        # 进行数据库写入
        cursor = connect.cursor()
        # SQL 插入语句
        write_sql = "insert into xige_hp_test.id_card(username,ID_card,modify_time,operator) values('%s','%s','%s','%s')" % (name, idcard, now, operator)
        # 执行sql语句
        sql.insert(write_sql, 'hupo_test')
        # cursor.close()
        # connect.close()
        print u"姓名是：" + name + u"，身份证号码随机生成成功：" + idcard
        return u"姓名是：" + name + u"，身份证号码随机生成成功：" + idcard,name,idcard

    except:
        return u"访问次数过多，请稍后再试~~~",'',''